﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using WinnerCMS.Common;
using EntityFramework.Extensions;
using WinnerCMS.Model;
using WinnerCMS.Model.Enum;

namespace WinnerCMS.Data
{
    /// <summary>
    /// 基本内容的方法集合
    /// </summary>
    public partial class CoreDal //: EFRepository<CoreInfo>
    {
        private static readonly CategoryDal MyDAL = new CategoryDal();


        #region 私有变量

        private Expression<Func<Core, Core>> NormalSelectEX = x => new Core
        {
            Id = x.Id,
            ContentTitle = x.ContentTitle,
            CategoryId = x.CategoryId,
            UpdateTime = x.UpdateTime,
            TemplateFileName = x.TemplateFileName
        };

        private Expression<Func<Core, Core>> selectEXForManage = c => new Core
        {
            Id = c.Id,
            ContentTitle = c.ContentTitle,
            Editor = c.Editor,
            IsOnTop = c.IsOnTop,
            IsElite = c.IsElite,
            IsHeadline = c.IsHeadline,
            IsSlide = c.IsSlide,
            UpdateTime = c.UpdateTime,
            CommentQuantity = c.CommentQuantity
        };

        #endregion

        #region  查找内容是否存在
        /// <summary>
        /// 查找内容是否存在
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public virtual int Exists(string title)
        {
            using (Entities db = new Entities())
            {
                return db.Cores.Where(x => x.ContentTitle == title).Select(x => x.Id).FirstOrDefault();
            }
        }
        #endregion

        #region 取得内容的基本属性

        /// <summary>
        /// 取得内容的基本属性
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Core GetInfo(int id)
        {
            using (var db = new Entities())
            {
                return db.Cores.SqlQuery(@"SELECT * FROM CMS_Cores WHERE Id={0}", id).FirstOrDefault();
            }
        }

        #endregion

        #region 执行批量操作

        /// <summary>
        /// 执行批量操作
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="which"></param>
        public void BatchToDo(IEnumerable<int> ids, BatchToDo which)
        {
            using (var db = new Entities())
            {
                if (which == WinnerCMS.Model.Enum.BatchToDo.删除)
                {
                    db.Database.ExecuteSqlCommand("update CMS_Cores set IsDeleted=1 where Id in (" + string.Join(",", ids) + ")");
                }
                else if (which == WinnerCMS.Model.Enum.BatchToDo.置顶或消顶)
                {
                    db.Database.ExecuteSqlCommand("update CMS_Cores set IsOnTop=1-IsOnTop where Id in (" + string.Join(",", ids) +
                                                  ")");
                }
                else if (which == WinnerCMS.Model.Enum.BatchToDo.推荐或消荐)
                {
                    db.Database.ExecuteSqlCommand("update CMS_Cores set IsElite=1-IsElite where Id in (" + string.Join(",", ids) + ")");
                }
                else if (which == WinnerCMS.Model.Enum.BatchToDo.审核或弃审)
                {
                    db.Database.ExecuteSqlCommand("update CMS_Cores set IsChecked=1-IsChecked where Id in (" + string.Join(",", ids) + ")");
                }
                else if (which == WinnerCMS.Model.Enum.BatchToDo.审核所有)
                {
                    db.Database.ExecuteSqlCommand("update CMS_Cores set IsChecked=1 where IsChecked=0");
                }
            }
        }

        #endregion

        #region  具有幻灯片属性的内容

        /// <summary>
        /// 具有幻灯片属性的内容
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="categoryIds"></param>
        /// <returns></returns>
        public IList<Core> SlideContents(int topNo, IEnumerable<int> categoryIds)
        {
            using (var db = new Entities())
            {
                var query = (from x in db.Cores
                             where !x.IsDeleted && x.IsChecked && x.IsSlide && categoryIds.Contains(x.CategoryId)
                             orderby x.UpdateTime descending
                             select new
                             {
                                 x.Id,
                                 x.ContentTitle,
                                 x.CategoryId,
                                 x.UpdateTime,
                                 x.PicUrl,
                                 x.TemplateFileName
                             }).Take(topNo).ToArray();
                return query.Select(x => new Core
                {
                    Id = x.Id,
                    ContentTitle = x.ContentTitle,
                    CategoryId = x.CategoryId,
                    UpdateTime = x.UpdateTime,
                    PicUrl = x.PicUrl,
                    TemplateFileName = x.TemplateFileName
                }).ToArray();
            }
        }

        #endregion

        #region 新内容列表

        /// <summary>
        /// 新内容列表
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="topNo"></param>
        /// <returns></returns>
        public IList<Core> Latests(int categoryId, int topNo)
        {
            IEnumerable<int> categoryIds = MyDAL.GetDescendantIds(categoryId);

            using (var db = new Entities())
            {
                db.Configuration.AutoDetectChangesEnabled = false;
                var query = (from x in db.Cores.AsNoTracking()
                             where !x.IsDeleted && x.IsChecked && categoryIds.Contains(x.CategoryId)
                             orderby x.UpdateTime descending
                             select new
                             {
                                 x.Id,
                                 x.ContentTitle,
                                 x.Brief,
                                 x.CategoryId,
                                 x.UpdateTime,
                                 x.PicUrl,
                                 x.TemplateFileName
                             }).Take(topNo).ToArray().Select(x => new Core
                    {
                        Id = x.Id,
                        ContentTitle = x.ContentTitle,
                        Brief = x.Brief,
                        CategoryId = x.CategoryId,
                        UpdateTime = x.UpdateTime,
                        PicUrl = x.PicUrl,
                        TemplateFileName = x.TemplateFileName
                    });


                return query.ToArray();
            }
        }

        #endregion

        #region 相关内容

        /// <summary>
        /// 相关内容
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="id"></param>
        /// <param name="Tags"></param>
        /// <returns></returns>
        public IList<Core> RelatedContent(int topNo, int id, string Tags)
        {
            if (Tags == null)
            {
                Tags = string.Empty;
            }
            using (var db = new Entities())
            {
                db.Configuration.AutoDetectChangesEnabled = false;

                string[] tags = Tags.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (tags.Length == 0)
                {
                    /* 等效算法
SELECT TOP 10 C.* FROM CMS_Cores C 
INNER JOIN CMS_CoreTags TI ON C.Id=TI.ContentId 
INNER JOIN CMS_CoreTags TI2 ON TI.TagID = TI2.TagID 
WHERE IsChecked=1 and TI2.ContentId=2995987
                     */
                    IQueryable<int> tag =
                        db.Tags.AsNoTracking().Where(x => x.Cores.Any(y => y.Id == id)).Select(x => x.Id);

                    var query =
                        db.Cores.AsNoTracking().Where(
                            x => x.TagsInfos.Any(y => tag.Contains(y.Id)))//&& x.Status==Issued
                          .Select(x => new
                          {
                              x.Id,
                              x.ContentTitle,
                              x.CategoryId,
                              x.UpdateTime,
                              x.TemplateFileName
                          });

                    return query.Take(topNo).ToArray().Select(x => new Core
                    {
                        Id = x.Id,
                        ContentTitle = x.ContentTitle,
                        CategoryId = x.CategoryId,
                        UpdateTime = x.UpdateTime,
                        TemplateFileName = x.TemplateFileName
                    }).ToArray();
                }
                /*
                     "select " + FIELDS + @" from CMS_Cores C with(nolock) WHERE IsChecked=1 and Id in (SELECT Top " + TopNo + " TI.ContentId FROM CMS_CoreTags TI INNER JOIN CMS_Tag T ON TI.TagID = T.Id where T.TagName in ('" + string.Join("',", tags) + "')  order by NEWID()) "
                     */
                var q = db.Cores.AsNoTracking().Where(x =>
                    db.Tags.Any(y => tags.Contains(y.TagName) && y.Cores.Any(z => z.Id == x.Id)))
                    .OrderBy(x => x.Id).Select(x => new
                    {
                        Id = x.Id,
                        x.ContentTitle,
                        CategoryId = x.CategoryId,
                        x.UpdateTime,
                        x.TemplateFileName
                    });
                return q.Take(topNo).ToArray().Select(x => new Core
                {
                    Id = x.Id,
                    ContentTitle = x.ContentTitle,
                    CategoryId = x.CategoryId,
                    UpdateTime = x.UpdateTime,
                    TemplateFileName = x.TemplateFileName
                }).ToArray();
            }
        }

        #endregion

        #region 上篇，下篇

        /// <summary>
        /// 上篇，下篇
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IList<Core> PreNextContents(int id)
        {
            using (var db = new Entities())
            {
                db.Configuration.AutoDetectChangesEnabled = false;

                var p =
                    db.Cores.AsNoTracking().Where(
                        c => c.Id == db.Cores.Where(y => y.Id < id).OrderByDescending(x => x.Id).Max(x => x.Id)).Select(
                        x =>
                            new
                            {
                                x.Id,
                                x.ContentTitle,
                                Brief = "上一页",
                                x.UpdateTime,
                                x.CategoryId,
                                x.TemplateFileName
                            }).ToArray().Select(
                            x =>
                                new Core
                                {
                                    Id = x.Id,
                                    ContentTitle = x.ContentTitle,
                                    Brief = x.Brief,
                                    UpdateTime = x.UpdateTime,
                                    CategoryId = x.CategoryId,
                                    TemplateFileName = x.TemplateFileName
                                });

                var n = db.Cores.AsNoTracking().Where(
                        c => c.Id == db.Cores.Where(y => y.Id > id).OrderBy(x => x.Id).Min(x => x.Id)).Select(
                        x =>
                            new
                            {
                                x.Id,
                                x.ContentTitle,
                                Brief = "上一页",
                                x.UpdateTime,
                                x.CategoryId,
                                x.TemplateFileName
                            }).ToArray().Select(
                            x =>
                                new Core
                                {
                                    Id = x.Id,
                                    ContentTitle = x.ContentTitle,
                                    Brief = x.Brief,
                                    UpdateTime = x.UpdateTime,
                                    CategoryId = x.CategoryId,
                                    TemplateFileName = x.TemplateFileName
                                });

                List<Core> list = new List<Core>()
                {
                    p.FirstOrDefault() ,n.FirstOrDefault() 
                };

                return list;
            }

        }

        #endregion

        #region 搜索内容

        /// <summary>
        /// 搜索内容
        /// </summary>
        /// <param name="sort"></param>
        /// <param name="keywords"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> Search(string sort, string[] keywords, PagingParam pp)
        {
            var couStr = new StringBuilder("SELECT COUNT(*) FROM CMS_Cores");
            couStr.Append(" WHERE IsChecked=1 ");

            if (keywords.Length > 0)
            {
                couStr.Append(" AND (");
                for (int i = 0; i < keywords.Length; i++)
                {
                    keywords[i] = string.Format("{0} LIKE '%{1}%'", sort, keywords[i]);
                }
                couStr.Append(string.Join(" OR ", keywords));
                couStr.Append(" ) ");
            }

            var sb = new StringBuilder();
            sb.AppendFormat(@"SELECT * FROM (SELECT *,ROW_NUMBER() Over(order by id Desc) rowId FROM CMS_Cores A WHERE IsChecked=1");

            if (keywords.Length > 0)
            {
                sb.Append(" AND (");
                sb.Append(string.Join(" OR ", keywords));
                sb.Append(" ) ");
            }
            sb.AppendFormat(" ) as _T where rowId between @p0 and @p1");


            using (var db = new Entities())
            {
                pp.RecordCount = db.Database.SqlQuery<int>(couStr.ToString()).First();

                var list =
                    db.Database.SqlQuery<Core>(sb.ToString(), pp.StartRecord, pp.EndRecord).ToArray();

                return list;
            }
        }

        #endregion

        #region 后台通用内容绑定

        /// <summary>
        /// 后台通用内容绑定
        /// </summary>
        /// <param name="where"></param>
        /// <param name="pp"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public IList<Core> BindList(string sort, string order, string @where, PagingParam pp)
        {
            using (var db = new Entities())
            {
                db.Configuration.ProxyCreationEnabled = false;


                var query = db.Cores.AsNoTracking().Where(@where);
                pp.RecordCount = query.Count();
                return query.OrderBy(sort + " " + order).Skip(pp.Skip).Take(pp.PageSize)
                    .Select(x => new { x.Id, x.ContentTitle, x.CategoryId, x.UpdateTime, x.IsElite, x.IsHeadline, x.IsOnTop, x.IsSlide, x.Editor, x.IsChecked, x.CommentQuantity }).ToArray()
                    .Select(x => new Core
                {
                    Id = x.Id,
                    ContentTitle = x.ContentTitle,
                    CategoryId = x.CategoryId,
                    IsElite = x.IsElite,
                    IsHeadline = x.IsHeadline,
                    IsOnTop = x.IsOnTop,
                    IsSlide = x.IsSlide,
                    UpdateTime = x.UpdateTime,
                    Editor = x.Editor,
                    IsChecked = x.IsChecked,
                    CommentQuantity = x.CommentQuantity
                }).ToArray();
            }

        }
        #endregion

        #region 删除或者还原

        /// <summary>
        /// 删除或者还原
        /// </summary>
        /// <param name="Ids"></param>
        /// <param name="itype"></param>
        public int[] DeleteAndUndelete(string Ids, int itype)
        {
            using (var db = new Entities())
            {
                string strSql = null;
                if (itype == 0) //单个或多个逻辑删除
                {
                    strSql = string.Format("update CMS_Cores set IsDeleted=1 where Id in ({0})", Ids);
                    db.Database.ExecuteSqlCommand(strSql);
                    return MyConvert.ConvertToArr(Ids);
                }

                if (itype == 1) //单个或多个物理删除
                {
                    strSql = string.Format("delete from CMS_CoreCategories where ContentId in ({0})", Ids);
                    db.Database.ExecuteSqlCommand(strSql);

                    strSql = string.Format("delete from CMS_Cores where Id in ({0})", Ids);
                    db.Database.ExecuteSqlCommand(strSql);

                    strSql = string.Format("delete from CMS_Comments where ContentId in ({0})", Ids);
                    db.Database.ExecuteSqlCommand(strSql);

                    strSql = string.Format("delete from CMS_CoreTags where ContentId in ({0})", Ids);
                    db.Database.ExecuteSqlCommand(strSql);
                    return MyConvert.ConvertToArr(Ids);
                }

                if (itype == 2) //还原所有
                {
                    int[] ids = db.Database.SqlQuery<int>("SELECT Id FROM CMS_Cores WHERE IsDeleted=1").ToArray();
                    strSql = string.Format("update CMS_Cores set IsDeleted=0 where IsDeleted=1");
                    db.Database.ExecuteSqlCommand(strSql);
                    return ids;
                }
                if (itype == 3) //还原选中
                {
                    strSql = string.Format("update CMS_Cores set IsDeleted=0 where Id in ({0}) AND IsDeleted=1",
                        Ids);
                    db.Database.ExecuteSqlCommand(strSql);
                    return MyConvert.ConvertToArr(Ids);
                }
                if (itype == 4) //清空回收站
                {
                    int[] ids = db.Database.SqlQuery<int>("SELECT Id FROM CMS_Cores WHERE IsDeleted=1").ToArray();
                    db.Database.ExecuteSqlCommand(
                        "delete from CMS_CoreTags where ContentId in (" + string.Join(",", ids) + ")");
                    db.Database.ExecuteSqlCommand(
                        "delete from CMS_Comments where ContentId in (" + string.Join(",", ids) + ")");

                    db.Database.ExecuteSqlCommand("delete from CMS_CoreCategories where ContentId in (" + string.Join(",", ids) + ")");
                    db.Database.ExecuteSqlCommand("delete from CMS_Cores where IsDeleted=1");
                    return ids;
                }
                throw new NotSupportedException("参数错误。");
            }
        }

        #endregion

        #region 批量移动内容到某栏目

        /// <summary>
        /// 批量移动内容到某栏目
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="categoryId"></param>
        public void MoveToNewCategory(string ids, int categoryId)
        {
            using (var db = new Entities())
            {
                db.Database.ExecuteSqlCommand("Update CMS_Cores set CategoryId={0} where Id in ( " + ids + " )",
                    categoryId);
            }
        }

        #endregion

        #region 批量移动问答到某专题

        /// <summary>
        /// 批量移动问答到某专题
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="specialId"></param>
        public void MoveToNewSpecial(string ids, int specialId)
        {
            using (var db = new Entities())
            {
                db.Database.ExecuteSqlCommand("Update CMS_Cores set SpecialID={0} where Id in ( " + ids + " )",
                    specialId);
            }
        }

        #endregion

        #region 用于批量替换

        /// <summary>
        /// 用于批量替换
        /// </summary>
        /// <param name="newContent"></param>
        /// <param name="id"></param>
        public void Replace(string newContent, int id)
        {
            using (var db = new Entities())
            {
                db.Database.ExecuteSqlCommand("update CMS_Cores set Content={0} where Id={1}", newContent, id);
            }
        }

        #endregion

        #region 修改属性

        /// <summary>
        /// 修改属性
        /// </summary>
        /// <param name="datas"></param>
        /// <param name="ids"></param>
        public void BatchUpData(dynamic datas, string ids)
        {
            var strSql = new StringBuilder();
            strSql.Append("UPDATE CMS_Cores SET ");

            int i = 0;
            var list = new List<object>();
            foreach (dynamic v in datas)
            {
                strSql.AppendFormat("{0}=@p{1}", "", i);
                list.Add(v.Data);
                i++;
            }

            using (var db = new Entities())
            {
                db.Database.ExecuteSqlCommand(
                    strSql.ToString().TrimEnd(',') + string.Format(" WHERE Id in ({0})", ids), list.ToArray());
            }
        }

        #endregion

        #region 回收站

        /// <summary>
        /// 回收站
        /// </summary>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> RecyclebinList(PagingParam pp)
        {
            using (var db = new Entities())
            {
                var query = db.Cores.Where(x => x.IsDeleted);

                pp.RecordCount = query.Count();

                return query.OrderBy(x => x.Id).Skip(pp.Skip).Take(pp.PageSize).ToArray();
            }
        }

        #endregion

        #region 栏目页绑定数据

        /// <summary>
        /// 栏目页绑定数据
        /// </summary>
        /// <param name="categoryIds"></param>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Core> CategoryPageBindList(IEnumerable<int> categoryIds, PagingParam pp)
        {
            using (var db = new Entities())
            {
                int classid = categoryIds.FirstOrDefault();
                var ontops = (from x in db.Cores.AsNoTracking()
                              where !x.IsDeleted && x.IsChecked && x.IsOnTop && x.CategoryId == classid
                              orderby x.UpdateTime descending
                              select new
                              {
                                  x.Id,
                                  x.Brief,
                                  x.ContentTitle,
                                  x.CategoryId,
                                  x.Hits,
                                  x.IsOnTop,
                                  x.IsElite,
                                  x.IsHeadline,
                                  x.IsSlide,
                                  x.Stars,
                                  x.UpdateTime,
                                  x.PicUrl,
                                  x.TemplateFileName
                              }).ToArray();

                var query = (from x in db.Cores.AsNoTracking()
                             where !x.IsDeleted && x.IsChecked && categoryIds.Contains(x.CategoryId)
                             orderby x.UpdateTime descending
                             select new
                             {
                                 x.Id,
                                 x.Brief,
                                 x.ContentTitle,
                                 x.CategoryId,
                                 x.Hits,
                                 x.IsOnTop,
                                 x.IsElite,
                                 x.IsHeadline,
                                 x.IsSlide,
                                 x.Stars,
                                 x.UpdateTime,
                                 x.PicUrl,
                                 x.TemplateFileName
                             });

                pp.RecordCount = query.Count();

                return
                    ontops.Concat(query.Skip(pp.Skip).Take(pp.PageSize).ToArray())
                        .Select(x => new Core
                        {
                            Id = x.Id,
                            Brief = x.Brief,
                            ContentTitle = x.ContentTitle,
                            CategoryId = x.CategoryId,
                            Hits = x.Hits,
                            IsOnTop = x.IsOnTop,
                            IsElite = x.IsElite,
                            IsHeadline = x.IsHeadline,
                            IsSlide = x.IsSlide,
                            Stars = x.Stars,
                            UpdateTime = x.UpdateTime,
                            PicUrl = x.PicUrl,
                            TemplateFileName = x.TemplateFileName
                        }).ToArray();
            }
        }

        #endregion



        #region 图文列表

        /// <summary>
        /// 图文列表
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="categoryIds"></param>
        /// <returns></returns>
        public IList<Core> PicContents(int topNo, IEnumerable<int> categoryIds)
        {
            using (var db = new Entities())
            {
                var query = (from x in db.Cores.AsNoTracking()
                             where !x.IsDeleted && x.IsChecked && x.IncludePic && categoryIds.Contains(x.CategoryId)
                             orderby x.UpdateTime descending
                             select new
                             {
                                 x.Id,
                                 x.ContentTitle,
                                 x.CategoryId,
                                 x.UpdateTime,
                                 x.TemplateFileName
                             }).Take(topNo).ToArray();

                return query.Select(x => new Core
                {
                    Id = x.Id,
                    ContentTitle = x.ContentTitle,
                    CategoryId = x.CategoryId,
                    UpdateTime = x.UpdateTime,
                    TemplateFileName = x.TemplateFileName
                }).ToArray();
            }
        }
        #endregion

        #region 热门内容

        /// <summary>
        /// 热门内容
        /// </summary>
        /// <param name="topNo">前N条</param>
        /// <param name="categoryId">筛选的栏目</param>
        /// <param name="begin">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="order">排序字段</param>
        /// <returns></returns>
        public IList<Core> HotContents(int topNo, int categoryId, DateTime begin, DateTime end, string order)
        {
            using (var db = new Entities())
            {
                string path = "|" + categoryId + "|";
                var query = (from x in db.Cores.AsNoTracking()
                             join y in db.Categoryes.AsNoTracking() on
                                 x.CategoryId equals y.Id
                             where !x.IsDeleted && x.IsChecked && x.LastHitTime >= begin && x.LastHitTime <= end &&
                                 y.Path.Contains(path)
                             select new
                             {
                                 Id = x.Id,
                                 x.ContentTitle,
                                 CategoryId = x.CategoryId,
                                 x.UpdateTime,
                                 x.TemplateFileName,
                                 x.WeekHits,
                                 x.MonthHits
                             }).Take(topNo);

                return query.OrderBy(string.Format("{0}Hits desc", order)).ToArray().Select(x => new Core
                {
                    Id = x.Id,
                    ContentTitle = x.ContentTitle,
                    CategoryId = x.CategoryId,
                    UpdateTime = x.UpdateTime,
                    TemplateFileName = x.TemplateFileName
                }).ToArray();
            }
        }

        #endregion

        #region 推荐内容

        /// <summary>
        /// 推荐内容
        /// </summary>
        /// <param name="topNo"></param>
        /// <param name="categoryIds">筛选栏目</param>
        /// <returns></returns>
        public IList<Core> EliteContents(int topNo, IEnumerable<int> categoryIds)
        {
            using (var db = new Entities())
            {
                var query = from x in db.Cores.AsNoTracking()
                            where !x.IsDeleted && x.IsChecked && x.IsElite && categoryIds.Contains(x.CategoryId)
                            orderby x.UpdateTime descending
                            select new { x.Id, x.CategoryId, x.ContentTitle, x.Hits, x.UpdateTime, x.TemplateFileName };
                return
                    query.Take(topNo).ToArray()
                        .Select(x =>
                                new Core
                                {
                                    Id = x.Id,
                                    CategoryId = x.CategoryId,
                                    ContentTitle = x.ContentTitle,
                                    Hits = x.Hits,
                                    UpdateTime = x.UpdateTime,
                                    TemplateFileName = x.TemplateFileName
                                }).ToArray();
            }
        }

        #endregion

        #region 头条内容

        /// <summary>
        /// 头条内容
        /// </summary>
        /// <param name="topNo">提取N条</param>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public IList<Core> HeadlineContents(int topNo, int categoryId)
        {
            string path = "|" + categoryId + "|";
            DateTime dt = DateTime.Now.AddDays(-60);
            using (var db = new Entities())
            {
                var query = from x in db.Cores.AsNoTracking()
                            join y in db.Categoryes.AsNoTracking() on x.CategoryId equals y.Id
                            where !x.IsDeleted && x.IsChecked && x.IsHeadline && y.Path.Contains(path) && x.UpdateTime >= dt
                            orderby x.UpdateTime descending
                            select new { x.Id, x.CategoryId, x.ContentTitle, x.Hits, x.UpdateTime, x.TemplateFileName };
                return query.Take(topNo).ToArray().Select(x =>
                                new Core
                                {
                                    Id = x.Id,
                                    CategoryId = x.CategoryId,
                                    ContentTitle = x.ContentTitle,
                                    Hits = x.Hits,
                                    UpdateTime = x.UpdateTime,
                                    TemplateFileName = x.TemplateFileName
                                }).ToArray();
            }
        }

        #endregion

        #region 更新点击数,并返回点击数

        /// <summary>
        /// 更新点击数,并返回点击数
        /// </summary>
        /// <param name="id">内容Id</param>
        /// <param name="upDataHits">是否更新点击数</param>
        /// <returns></returns>
        public int UpDateHits(int id, bool upDataHits)
        {
            using (var db = new Entities())
            {
                var info = db.Cores.SqlQuery("SELECT * FROM CMS_Cores WHERE Id={0}", id).FirstOrDefault();
                if (info == null)
                {
                    return 0;
                }
                if (upDataHits == false)
                {
                    return info.Hits;
                }

                info.Hits = info.Hits + 1;

                if (MyDateTime.DateDiff(DateDiffOption.Day, DateTime.Now, info.LastHitTime) <= 0)
                {
                    info.DayHits = info.DayHits + 1;
                }

                if (MyDateTime.DateDiff(DateDiffOption.Week, DateTime.Now, info.LastHitTime) <= 0)
                {
                    info.WeekHits = info.WeekHits + 1;
                }

                if (MyDateTime.DateDiff(DateDiffOption.Month, DateTime.Now, info.LastHitTime) <= 0)
                {
                    info.MonthHits = info.MonthHits + 1;
                }
                info.LastHitTime = DateTime.Now;

                db.SaveChangesAsync().Wait();

                return info.Hits;
            }
        }

        #endregion

        #region 更新评论数量

        /// <summary>
        /// 更新评论信息
        /// </summary>
        /// <param name="contentId"></param>
        public void UpdateCommentInfo(int contentId)
        {
            using (var db = new Entities())
            {
                var info = (from x in db.Comments
                            where x.ContentId == contentId
                            group x by x.ContentId
                                into g
                                select new { iCount = g.Count(), iSum = g.Sum(a => a.Score) }).FirstOrDefault();
                if (info == null)
                {
                    return;
                }

                db.Database.ExecuteSqlCommand(
                    "UPDATE CMS_Cores SET CommentQuantity={0},CommentScore={1} WHERE Id={2}", info.iCount,
                    info.iSum, contentId);
            }
        }

        #endregion
    }
}